"""
接口服务模块：用户信息
"""

import pickle

from app.common.exception import InvalidUserException
from app.common.constants import (SysConfigConstants, Switch)
from app.common.redis import redis_cli
from app.setting import TOKEN_REDIS_EXPIRE_TIME
from app.utils.stringutil import (verify_password, generate_token)
from app.service.userinfo import UserInfoService
from app.service.sysconfig import SysConfigService


class UserInfoApiService(object):
    """
    用户信息api service类
    """

    @classmethod
    def page_by_param(cls, page=1, page_size=10, **kwargs):
        data = UserInfoService.page_by_param(page, page_size, **kwargs)
        result = dict(code=0, msg="", data=data)
        return result

    @classmethod
    def login(cls, name, password):
        """
        用户登录
        :param name:
        :param password:
        :return:
        """

        user = UserInfoService.find_by_name(name)
        if not user:
            raise InvalidUserException("用户不存在")

        if not verify_password(user['password'], password):
            raise InvalidUserException("密码错误")

        # 生成临时的user_token
        user_token = generate_token()

        # 获取静态服务器信息
        nid = 'image_server_url'
        sys_type = SysConfigConstants.Type.SYS.value[0]
        sys_status = Switch.YES.value[0]
        sys_config = SysConfigService.find_by_nid_and_type_and_status(nid=nid, type_=sys_type, status=sys_status)
        image_server_url = sys_config.get('value', '') if sys_config else ''

        user_info = dict(
            token=user_token,
            name=user['name'],
            avatar=image_server_url + user['avatar']

        )

        redis_cli.set(user_token, pickle.dumps(user_info))
        redis_cli.expire(user_token, TOKEN_REDIS_EXPIRE_TIME)

        result = dict(code=0, msg="", user=user_info)
        return result

    @classmethod
    def logout(cls, token):
        """
        用户登出
        :return:
        """

        if token:
            redis_cli.delete(token)

        result = dict(code=0, msg="注销成功")
        return result
